package com.codeyang.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.codeyang.constant.AliSmsConstant;
import com.codeyang.constant.QueueConstant;
import com.codeyang.model.AliSmsModel;
import com.codeyang.service.SmsLogService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

/**
 * 描述: 阿里短信发送MQ队列监听,世纪发送短信的操作
 *
 * @author CodeYang_Site
 * @version 2021/5/30 14:03
 */
@Slf4j
@Component
public class AliSmsListener {


    @Autowired
    private IAcsClient acsClient;

    @Autowired
    private SmsLogService smsLogService;

    @RabbitListener(queues = QueueConstant.PHONE_SEN_QUEUE, concurrency = "3-5")
    public void handlerSms(Message message, Channel channel) {
        //1.拿投递id
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        //2处理
        log.info("有短信消息进入");
        String msg = new String(message.getBody());
        //3.转换一下 消息内容
        JSONObject jsonObject = JSON.parseObject(msg);
        //4.解析json
        String userId = jsonObject.getString(AliSmsConstant.USERID);
        String aliSmsModelJson = jsonObject.getString(AliSmsConstant.ALI_SMS_MODEL);
        AliSmsModel aliSmsModel = JSON.parseObject(aliSmsModelJson, AliSmsModel.class);
        //5.真正发送短信
        SendSmsResponse sendSmsResponse = realSendMsg(aliSmsModel);
        // 不管发送的返回结果是不是成功,咋们都记录到DB去,这样也可以 确认发送短信的丢失率和发现短信丢失的记录
        if (ObjectUtils.isEmpty(sendSmsResponse)) {
            // 记录数据库
            smsLogService.saveAliSms(userId, aliSmsModel, sendSmsResponse);
        }
        try {
            //签收一下,消息,不管怎么样,都需要签收一下消息,避免队列消息过多
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 真正发送短信操作,向阿里云发送短信
     *
     * @param aliSmsModel
     * @return
     */
    private SendSmsResponse realSendMsg(AliSmsModel aliSmsModel) {
        //组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        //使用post提交
        request.setMethod(MethodType.POST);
        //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式；发送国际/港澳台消息时，接收号码格式为国际区号+号码，如“85200000000”
        request.setPhoneNumbers(aliSmsModel.getPhoneNumbers());
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(aliSmsModel.getSignName());
        //必填:短信模板-可在短信控制台中找到，发送国际/港澳台消息时，请使用国际/港澳台短信模版
        request.setTemplateCode(aliSmsModel.getTemplateCode());
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
        //参考：request.setTemplateParam("{\"变量1\":\"值1\",\"变量2\":\"值2\",\"变量3\":\"值3\"}")
        request.setTemplateParam(aliSmsModel.getTemplateParam());

        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (ClientException e) {
            log.error("发送失败,手机号为:{}", aliSmsModel.getPhoneNumbers());
            e.printStackTrace();
        }
        //        if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
        //        //请求成功
        //        }
        return sendSmsResponse;
    }
}


